﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Text;
using System.IO;
//using x1.Framework;

public class BuildAssetBundle{

    private const string VERSION = "version.txt";

    //AB版本文件
    private const string AB_VERSION = "AB_version.txt";

    private const string Lua_VERSION = "Lua_version.txt";


    /// <summary>
    /// 打包AssetBundle
    /// </summary>
    /// <param name="sourcePath">资源路径</param>
    /// <param name="outPath">输出路径</param>
    /// <param name="target">平台</param>
    /// <param name="isClear">是否清理输出路劲</param>
    public static void Buiid(string sourcePath, string outPath, BuildTarget target,bool isClear = true)
    {
        //SetAssetBundleNameByFloder(IO.GetFiles(sourcePath), sourcePath);

        string outPutPath = Path.Combine(outPath, Platform.GetPlatformFolder(target));

        if(isClear)
        {
            IO.DeleteFiles(outPutPath);
        }

        if(!Directory.Exists(outPutPath))
        {
            Directory.CreateDirectory(outPutPath);
        }

        BuildPipeline.BuildAssetBundles(outPutPath, 0, target);
        AssetDatabase.Refresh();
        //string fileName = "AB_" + Platform.GetPlatformFolder(target) + "_version.txt";
        //string savePath = Application.streamingAssetsPath;
        //CreateVersionFile(outPutPath,savePath, fileName);
        //AssetDatabase.Refresh();

        //BuildABByAes(sourcePath, outPath, target, isClear);

        //if(target == BuildTarget.StandaloneWindows64  || target == BuildTarget.StandaloneWindows)
        //{
        //    //如果是windows平台
        //    string path = Application.persistentDataPath + "/Res/Windows";
        //    if (!Directory.Exists(path))
        //    {
        //        Directory.CreateDirectory(path);
        //    }
        //    else
        //    {
        //        //Directory.Delete(path);
        //        IO.DeleteDirectory(path);
        //        Directory.CreateDirectory(path);
        //    }
        //    IO.CopyOldLabFilesToNewLab(outPutPath,path);
        //    //Loger.Info()
        //    Debug.Log(path);
        //}
    }

    /// <summary>
    /// 拷贝lua脚本
    /// </summary>
    public static void CopyLuaRes()
    {
        string path = Application.persistentDataPath + "/Res/Lua";
        string sourPath = Application.dataPath + "/Lua";
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        else
        {
            IO.DeleteDirectory(path);
            Directory.CreateDirectory(path);
        }
        IO.CopyOldLabFilesToNewLab(sourPath, path);
        Debug.Log(path);
    }




    /// <summary>
    /// 打包Lua资源
    /// </summary>
    public static void BuildLuaRes()
    {
        //string targetPath = Application.streamingAssetsPath + "/Lua";
        ////string targetPath = Application.dataPath + "/UI/Lua";
        //Debug.Log("---targetPath:" + targetPath);
        //IO.CopyLuaDirecory2(AppConfig.LUA_RES_LOCAL, targetPath + "/");
        //CreateVersionFile(targetPath);

        string sourcePath = Application.dataPath + "/Lua";
        string savePath = Application.streamingAssetsPath + "/Lua";

        IO.CreateLuaRes(sourcePath, savePath);


        AssetDatabase.Refresh();
    }


    /// <summary>
    /// 打包加密AB资源
    /// </summary>
    public static void BuildABByAes(string sourcePath, string outPath, BuildTarget target, bool isClear = true)
    {
        //Buiid(sourcePath, outPath, target);
        //string savePath = Application.streamingAssetsPath + "/" + Platform.GetPlatformFolder(target);
        //string resPath = Application.streamingAssetsPath + "/" + Platform.GetPlatformFolder(target);

        string resPath = Path.Combine(outPath, Platform.GetPlatformFolder(target) + "_Res");

        string savePath = Path.Combine(outPath, Platform.GetPlatformFolder(target));

        IO.CreateABByAES(resPath, savePath, Platform.GetPlatformFolder(target));

        string fileName = "AB_" + Platform.GetPlatformFolder(target) + "_version.txt";
        string savePathVersion = Application.streamingAssetsPath;
        CreateVersionFile(savePath, savePathVersion, fileName);

        AssetDatabase.Refresh();
    }



    /// <summary>
    /// 生成版本文件
    /// </summary>
    public static void BuildVersion()
    {
        string luaRes = Application.dataPath + "/Lua";
        string savePath = Application.streamingAssetsPath;
        CreateVersionFile(luaRes, savePath,Lua_VERSION);
        AssetDatabase.Refresh();
    }


    /// <summary>
    /// 打包ZIP
    /// </summary>
    public static void BuildZip()
    {
        //string path = Application.streamingAssetsPath + "/Lua";
        //string name = Application.streamingAssetsPath + "/Lua/CreateRoomView.lua.txt";
        //string name = "CreateRoomView.lua.txt";
        //string path = Application.streamingAssetsPath;
        //bool result = ZipHelper.Zip(path, "Res.zip", "123456");
        //if(result)
        //{
        //    //打包成功后把压缩包转移到streamingAssetsPath目录
        //    string savePaath = Application.dataPath;
        //    string[] strs = savePaath.Split('/');
        //    savePaath = savePaath.Substring(0, savePaath.Length - strs[strs.Length - 1].Length);
        //    savePaath = savePaath + "Res.zip";
        //    Loger.Info("savePath:" + savePaath);
        //    IO.CopyFile(savePaath, Application.streamingAssetsPath + "/");
        //    IO.DeleteFiles(savePaath);
        //}
        //Loger.Special("zip:" + result);

        string luaSourcePath = Application.dataPath + "/Lua";
        string path = Application.streamingAssetsPath;
        string name = path + "/Res.zip";
        //吧lua文件拷贝到streamingAssetsPath下
        //IO.CopyOldLabFilesToNewLab(luaSourcePath, path + "/Lua");
        //FZipHelper.Zip(Application.dataPath + "/Res.zip", path);
        IO.CopyFile(Application.dataPath + "/Res.zip", Application.streamingAssetsPath + "/", true);
        //IO.DeleteFiles(luaSourcePath);
        AssetDatabase.Refresh();
        //Directory.Delete(path + "/Lua");
        IO.DeleteDirectory(path + "/Lua");
        AssetDatabase.Refresh();
        //UnZip();
    }


    public static void UnZip()
    {
        string path = Application.dataPath + "/Lua.zip";
        string dir = Application.dataPath + "/Lua";
        Loger.Info("BuildAssetBundle", "path:" + path);
        //bool result = ZipHelper.UnZip(path, dir, "123456");
        //FZipHelper.UnZip(Application.dataPath + "/Res.zip", dir);
        //Loger.Info("unzip:" + result);
    }


    /// <summary>
    /// 创建版本文件
    /// </summary>
    private static void CreateVersionFile(string resPath)
    {
        Dictionary<string, int> numDic = new Dictionary<string, int>();
        Dictionary<string, string> md5Dic = new Dictionary<string, string>();
        if (File.Exists(resPath + "/" + VERSION))
        {
            Debug.Log("....version is exit...");
            string[] array = File.ReadAllLines(resPath);
            foreach (var str in array)
            {
                string[] strs = str.Split('|');
                numDic.Add(strs[0], int.Parse(strs[2]));
                md5Dic.Add(strs[0], strs[1]);
            }
        }
        else
        {
            Debug.Log(".....version is  not exit...");
        }

        StringBuilder versions = new StringBuilder();
        foreach (var file in IO.GetFiles(resPath))
        {
            if (Path.GetExtension(file) != ".manifest")
            {
                string md5 = IO.GetFileMD5(file);
                string assetName = file.Substring(resPath.Length + 1, file.Length - resPath.Length - 1);
                if (numDic.ContainsKey(assetName))
                {
                    if (md5 != md5Dic[assetName])
                    {
                        int num = numDic[assetName] + 1;
                        versions.Append(assetName).Append("|").Append(md5).Append("|").Append(num).Append("\n");
                    }
                    else
                    {
                        int num = numDic[assetName];
                        versions.Append(assetName).Append("|").Append(md5).Append("|").Append(num).Append("\n");
                    }
                }
                else
                {
                    versions.Append(assetName).Append("|").Append(md5).Append("|").Append(0).Append("\n");
                }
            }
            else
            {
                IO.DeleteFiles(file);
            }
        }
        FileStream fs = new FileStream(resPath + "/" + VERSION, FileMode.Create);
        byte[] bytes = Encoding.UTF8.GetBytes(versions.ToString());
        fs.Write(bytes, 0, bytes.Length);
        fs.Flush();
        fs.Close();
    }



    /// <summary>
    /// 创建版本文件
    /// </summary>
    private static void CreateVersionFile(string resPath,string savePath,string fileName)
    {
        Dictionary<string, int> numDic = new Dictionary<string, int>();
        Dictionary<string, string> md5Dic = new Dictionary<string, string>();
        if (File.Exists(resPath + "/" + VERSION))
        {
            Debug.Log("....version is exit...");
            string[] array = File.ReadAllLines(resPath);
            foreach (var str in array)
            {
                string[] strs = str.Split('|');
                numDic.Add(strs[0], int.Parse(strs[2]));
                md5Dic.Add(strs[0], strs[1]);
            }
        }
        else
        {
            Debug.Log(".....version is  not exit...");
        }

        StringBuilder versions = new StringBuilder();
        foreach (var file in IO.GetFiles(resPath))
        {
            if (Path.GetExtension(file) != ".manifest")
            {
                string md5 = IO.GetFileMD5(file);
                string assetName = file.Substring(resPath.Length + 1, file.Length - resPath.Length - 1);
                if (numDic.ContainsKey(assetName))
                {
                    if (md5 != md5Dic[assetName])
                    {
                        int num = numDic[assetName] + 1;
                        versions.Append(assetName).Append("|").Append(md5).Append("|").Append(num).Append("\n");
                    }
                    else
                    {
                        int num = numDic[assetName];
                        versions.Append(assetName).Append("|").Append(md5).Append("|").Append(num).Append("\n");
                    }
                }
                else
                {
                    versions.Append(assetName).Append("|").Append(md5).Append("|").Append(0).Append("\n");
                }
            }
            else
            {
                IO.DeleteFiles(file);
            }
        }
        FileStream fs = new FileStream(savePath + "/" + fileName, FileMode.Create);
        byte[] bytes = Encoding.UTF8.GetBytes(versions.ToString());
        fs.Write(bytes, 0, bytes.Length);
        fs.Flush();
        fs.Close();
    }



    private static void SetAssetBundleNameByFloder(string[] files,string sourcePath)
    {
        Debug.Log("sourcePath:" + sourcePath);
        foreach (var item in files)
        {
            string filePath = item.Substring(sourcePath.Length + 1);
            Debug.Log("filePath:" + filePath);
            string[] strs = filePath.Split('/');
            string abName = filePath.Substring(0, filePath.Length - strs[strs.Length - 1].Length - 1);
            Debug.Log("abName:" + abName);
            //abName = abName.Remove('/','.');

            string assetPath = "Assets" + item.Substring(Application.dataPath.Length);

            AssetImporter importer = AssetImporter.GetAtPath(assetPath);
            importer.assetBundleName = abName + ".assetbundle";
        }
    }

}
